package com.dycong.common.network;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Map;

/**
 * Created by Yu on 2015/4/2.
 */
public class ResettableStreamHttpServletRequest extends
        HttpServletRequestWrapper {


    private byte[] rawData;
    private HttpServletRequest request;
    private ResettableServletInputStream servletStream;

    Map<String, String> paramMap;

    private Logger logger = Logger.getLogger(ResettableStreamHttpServletRequest.class);

    public ResettableStreamHttpServletRequest(HttpServletRequest request) {
        super(request);
        this.request = request;
        this.servletStream = new ResettableServletInputStream();
    }

    public void resetInputStream() {
        servletStream.stream = new ByteArrayInputStream(rawData);
    }

    public byte[] getRawData() {
        if (rawData==null){
            try {
                initRawData();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rawData;
    }

    private void initRawData() throws IOException {
        if (rawData == null) {
            rawData = IOUtils.toByteArray(request.getInputStream());
            if (logger.isTraceEnabled()) {
                logger.trace("UTF8 >>> " + new String(rawData, "UTF-8"));
            }
        }
        servletStream.stream = new ByteArrayInputStream(rawData);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        initRawData();
        return servletStream;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        initRawData();
        return new BufferedReader(new InputStreamReader(servletStream));
    }




    @Override
    public String[] getParameterValues(String name) {
        String parameter = getParameter(name);
        if (parameter == null)
            parameter = "";
        return parameter.split(";");
    }

    private class ResettableServletInputStream extends ServletInputStream {

        private InputStream stream;

        @Override
        public int read() throws IOException {
            return stream.read();
        }

//        @Override
//        public boolean isFinished() {
//            return true;
//        }
//
//        @Override
//        public boolean isReady() {
//            return true;
//        }
//
//        @Override
//        public void setReadListener(ReadListener readListener) {
//
//        }
    }
}